package com.springapp.mvc.services;

import com.springapp.mvc.dao.CommentsDao;
import com.springapp.mvc.dao.PostsDao;
import com.springapp.mvc.entity.CommentForPost;
import com.springapp.mvc.entity.Post;
import com.springapp.mvc.entity.UserPost;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.UUID;


@Component
public class PostingServiceImpl implements PostingService {

    public static final Path FILE_STORAGE_PATH = Paths.get("C:", "Temp", "imageStore");

    @PostConstruct
    public void createFileStorageDirectoryIfRequired() {
        try {
            Files.createDirectories(FILE_STORAGE_PATH);
        } catch (IOException e) {
            // log it and fall silently
            throw new RuntimeException("Error creating directory to store files: " + FILE_STORAGE_PATH);
        }
    }

    @Autowired
    PostsDao postsDao;

    @Autowired
    CommentsDao commentsDao;

    @Override
    public List<UserPost> getPosts(Long start, Long end) {
        return postsDao.getPosts(start, end);
    }

    @Override
    public void addMessage(Long userId, String messageText) {
        postsDao.addPost(userId, messageText, null);
    }

    @Override
    @PreAuthorize("hasRole('ROLE_SUPERVISOR')")
    public void addMessage(Long userId, String messageText, byte[] imageBytes) throws IOException {
        String fileUniqueName = UUID.nameUUIDFromBytes(imageBytes).toString();

        Files.write(FILE_STORAGE_PATH.resolve(fileUniqueName), imageBytes, StandardOpenOption.CREATE);

        postsDao.addPost(userId, messageText, fileUniqueName);
    }

    @Override
    public void createComment(Long postId, Long userId, String comment) {
        commentsDao.createComment(postId, userId, comment);
    }

    @Override
    public List<CommentForPost> getCommentsForPost(Long postId) {
        return commentsDao.getCommentsForPost(postId);
    }

    @Override
    public Post getPostById(Long postId) {
        return postsDao.getPostById(postId);
    }

    @Override
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public void deleteMessage(Long postId) {
        postsDao.deleteMessage(postId);
    }

    @Override
    @PreAuthorize("hasRole('ROLE_SUPERVISOR')")
    public void editMessage(Long postId, String newText) {
        postsDao.editMessage(postId,newText);
    }
}
